<template>
  <el-form
    ref="form1"
    :rules="rules"
    :model="saleline"
    class="demo-form-inline"
    label-width="100px"
  >
    <el-form-item label="线索标签：" style="display:block;">
      <NewTags
        v-if="tagsArr.length"
        :data="tagsArr"
        :init-data="initDataArr"
        @changeTag="changeLabel"
      />
    </el-form-item>
    <el-form-item label="选择会员：" prop="memberName">
      <el-autocomplete
        v-model="saleline.memberName"
        :fetch-suggestions="querySearchAsync"
        placeholder="选择会员"
        :disabled="!isCreate"
        @select="handleSelect"
      />
    </el-form-item>
    <el-form-item label="选择商机：" prop="projectName">
      <el-autocomplete
        v-model="saleline.projectName"
        :fetch-suggestions="querySearchAsync1"
        placeholder="选择商机"
        @select="handleSelect1"
      />
    </el-form-item>
    <el-form-item label="来源：" prop="source">
      <el-input v-model="saleline.source" :disabled="!isCreate" placeholder="来源" />
    </el-form-item>
    <el-form-item label="备注：">
      <el-input v-model="saleline.remark" placeholder="备注" />
    </el-form-item>
    <el-form-item label="阶段名称：" prop="salesStage">
      <el-select v-model="saleline.salesStage" clearable placeholder="阶段名称">
        <el-option
          v-for="item in saleStage"
          :key="item.dicCode"
          :label="item.dicName"
          :value="item.dicCode"
        />
      </el-select>
    </el-form-item>
    <div style="display:flex;justify-content:center;">
      <el-button style="margin:25px 0;" type="primary" @click="submit">保 存</el-button>
    </div>
  </el-form>
</template>

<script>
import NewTags from '~/components/commom/newTags';
import regular from '~/utils/regular';
import mmUrl from '~/utils/utilUrl';
export default {
  components: {
    NewTags
  },
  props: ['id'],
  data() {
    return {
      isCreate: this.$props.id === 'create',
      editor: this.$props.id === 'create',
      initDataArr: [],
      restaurants1: [],
      restaurants: [],
      rules: {
        salesStage: regular.requireChange,
        source: regular.require1,
        projectName: {
          trigger: 'change',
          validator: this.checkConnect1
        },
        memberName: {
          trigger: 'change',
          validator: this.checkConnect
        }
      },
      saleStage: [],
      saleline: {
        id: '',
        memberId: '',
        label: '',
        projectId: '',
        executor: '',
        salesStage: '',
        remark: '',
        memberName: '',
        projectName: '',
        source: '',
        saleStage: []
      },
      tagsArr: []
    }
  },
  mounted() {
    this.getInit()
    this.getLabel()
    this.loadCreate()
  },
  methods: {
    submit() {
      this.$refs['form1'].validate(valid => {
        if (valid) {
          if (this.restaurants1) {
            if (
              !this.restaurants1.some(
                v => v.value === this.saleline.projectName
              )
            ) {
              this.saleline.projectId = '';
            }
          }
          this.$post({
            url: this.isCreate ? mmUrl.sales.create : mmUrl.sales.editor,
            data: {
              item: this.saleline
            }
          })
            .then(res => {
              this.$message({
                type: 'success',
                message: '操作成功'
              })
              this.$emit('closeDialog')
            })
            .catch(err => this.$message.error(err))
        }
      })
    },
    getInit() {
      this.isCreate
        ? ''
        : this.$post({
          url: '/manage/saleslead/loadViewSalesLeadPage',
          data: {
            id: this.$props.id
          }
        }).then(res => {
          this.saleline = res.item
            this.initDataArr = res.item.label ? JSON.parse(res.item.label) : '';
        })
    },
    loadCreate() {
      this.$post({
        url: mmUrl.sales.loadCreate,
        data: {}
      })
        .then(res => {
          this.saleStage = res.dics[0].children
        })
        .catch(err => this.$message.error(err))
    },
    getLabel() {
      this.$post({
        url: mmUrl.label.pageLoad,
        data: {
          keyword: '',
          page: {
            maxResultCount: 0,
            pageNo: 0,
            pageSize: 10,
            skipCount: 0
          },
          type: 0
        }
      }).then(res => {
        this.tagsArr = res.items.items
      })
    },
    checkConnect(rule, value, callback) {
      if (!this.isCreate) {
        callback()
      }
      if (value === '') {
        callback(new Error('此项为必填项'))
      } else if (this.restaurants.some(v => v.value === value)) {
        callback()
      } else {
        callback(new Error('请填写正确的内容'))
      }
    },
    checkConnect1(rule, value, callback) {
      if (!this.isCreate) {
        callback()
      }
      if (value === '') {
        callback(new Error('此项为必填项'))
      } else if (this.restaurants1.some(v => v.value === value)) {
        callback()
      } else {
        callback(new Error('请填写正确的内容'))
      }
    },
    async querySearchAsync1(queryString, cb) {
      queryString
        ? await this.$get({
          url: '/manage/project/getProjectByLikeName',
          data: {
            proName: queryString
          }
        }).then(res => {
          this.restaurants1 = res.map(v => ({
            value: v.projectName,
            id: v.id
          }))
          })
        : '';
      clearTimeout(this.timeout)
      this.timeout = setTimeout(() => {
        cb(this.restaurants1)
      }, 300 * Math.random())
    },
    handleSelect1(item) {
      this.saleline.projectId = item.id
      this.saleline.projectName = item.value
    },
    async querySearchAsync(queryString, cb) {
      queryString
        ? await this.$get({
          url: '/manage/member/getLikeMemberName',
          data: {
            keyword: queryString
          }
        }).then(res => {
          this.restaurants = res.map(v => ({ value: v.nickName, id: v.id }))
          })
        : '';
      clearTimeout(this.timeout)
      this.timeout = setTimeout(() => {
        cb(this.restaurants)
      }, 300 * Math.random())
    },
    handleSelect(item) {
      this.saleline.memberId = item.id
      this.saleline.memberName = item.value
    },
    changeLabel(res) {
      this.saleline.label = JSON.stringify(res)
    }
  }
}
</script>

<style>
</style>
